﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestWim.TestWimCL.POCO;
using TestWim.TestWimCL.DAL;

namespace TestWim.TestWimMvc.Controllers
{
  public class MeetingController : Controller
  {
    private EFDbContext db = new EFDbContext();

    //
    // GET: /Meeting/

    public ViewResult Index()
    {
      return View(db.Meetings.ToList());
    }

    //
    // GET: /Meeting/Details/5

    public ViewResult Details(int id)
    {
      Meeting meeting = db.Meetings.Include("Results").Single(x => x.MeetingId == id);
      Dictionary<Event, List<Result>> graphData = new Dictionary<Event, List<Result>>();
      List<Result> results=meeting.Results.ToList();
      IEnumerable<IGrouping<int,Result>> query=results.GroupBy(x => x.EventId);
      //Console.WriteLine("Begin Grouping");
      foreach (IGrouping<int, Result> group in query)
      {
        graphData.Add(group.First().Event, group.ToList());
        /*Console.WriteLine(group.Key);
        foreach (Result r in group)
        {
          Console.WriteLine("\t{0} - {1} - {2}", r.ResultId, r.ResultValue, r.Student.Name);
        }*/
      }
      ViewBag.GraphData = graphData;
      return View(meeting);
    }

    //
    // GET: /Meeting/Create

    public ActionResult Create()
    {
      return View();
    }

    //
    // POST: /Meeting/Create

    [HttpPost]
    public ActionResult Create(Meeting meeting)
    {
      if (ModelState.IsValid)
      {
        db.Meetings.Add(meeting);
        db.SaveChanges();
        return RedirectToAction("Index");
      }

      return View(meeting);
    }

    //
    // GET: /Meeting/Edit/5

    public ActionResult Edit(int id)
    {
      Meeting meeting = db.Meetings.Find(id);
      return View(meeting);
    }

    //
    // POST: /Meeting/Edit/5

    [HttpPost]
    public ActionResult Edit(Meeting meeting)
    {
      if (ModelState.IsValid)
      {
        db.Entry(meeting).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
      }
      return View(meeting);
    }

    //
    // GET: /Meeting/Delete/5

    public ActionResult Delete(int id)
    {
      Meeting meeting = db.Meetings.Find(id);
      return View(meeting);
    }

    //
    // POST: /Meeting/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
      Meeting meeting = db.Meetings.Find(id);
      db.Meetings.Remove(meeting);
      db.SaveChanges();
      return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
      db.Dispose();
      base.Dispose(disposing);
    }
  }
}